package com.library.controller;

import com.library.entity.Book;
import com.library.service.BookService;
import com.library.util.ResultUtil;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/api/books")
public class BookController {
    @Resource
    private BookService bookService;

    // 新增图书 - 修复@RequestBody注解
    @PostMapping
    public ResultUtil<?> addBook(@RequestBody Book book) {  // 修正：RequestBodyRequestBody -> RequestBody
        boolean success = bookService.addBook(book);
        if (success) {
            return ResultUtil.success("图书新增成功");
        } else {
            return ResultUtil.error("ISBN已存在");
        }
    }

    // 更新图书 - 修复@RequestBody注解
    @PutMapping("/{id}")
    public ResultUtil<?> updateBook(@PathVariable Long id, @RequestBody Book book) {  // 修正：RequestBodyBody -> RequestBody
        book.setId(id);
        boolean success = bookService.updateBook(book);
        if (success) {
            return ResultUtil.success("图书更新成功");
        } else {
            return ResultUtil.error("图书不存在或ISBN重复");
        }
    }

    // 删除图书
    @DeleteMapping("/{id}")
    public ResultUtil<?> deleteBook(@PathVariable Long id) {
        boolean success = bookService.deleteBook(id);
        if (success) {
            return ResultUtil.success("图书删除成功");
        } else {
            return ResultUtil.error("图书不存在");
        }
    }

    // 按ID查询
    @GetMapping("/{id}")
    public ResultUtil<Book> getBookById(@PathVariable Long id) {
        Book book = bookService.getBookById(id);
        ResultUtil<Book> result = new ResultUtil<>();
        if (book != null) {
            result.setCode(0);
            result.setMessage("操作成功");
            result.setData(book);
        } else {
            result.setCode(1);
            result.setMessage("图书不存在");
            result.setData(null);
        }
        return result;
    }

    // 按条件搜索
    @GetMapping("/search")
    public ResultUtil<List<Book>> searchBooks(@RequestParam Map<String, Object> condition) {
        List<Book> books = bookService.getBookByCondition(condition);
        return ResultUtil.success(books);
    }

    // 查询所有
    @GetMapping
    public ResultUtil<List<Book>> getAllBooks() {
        List<Book> books = bookService.getAllBooks();
        return ResultUtil.success(books);
    }
}
